// Copyright 2012 Google Inc. All Rights Reserved.

package com.google.appengine.syncserver.entities;

import org.codehaus.jackson.annotate.JsonCreator;
import org.codehaus.jackson.annotate.JsonIgnore;
import org.codehaus.jackson.annotate.JsonProperty;


/**
 * PreferencesValue used for storing shared preferences. Also includes the
 * version when the value was updated.
 */
public class PreferencesValue {

  // Json field for storing the preference value;
  private static final String VALUE_FIELD = "value";

  // Json field for storing the preference version;
  private static final String VERSION_FIELD = "version";

  // Json field for storing whether the preference key has been deleted.
  private static final String DELETED_FIELD = "deleted";

  /**
   * Set to true if this value represents a deleted entry.
   */
  private boolean deleted;

  /**
   * Value is valid only if isDeleted is false.
   */
  private String value;

  /**
   * Max update version number when the value gets written to data-store.
   */
  private long version;

  /**
   * Allow the specification of value without the version.
   *
   * @param value
   */
  public PreferencesValue(String value) {
    this.value = value;
    this.version = 0;
    this.deleted = false;
  }

  @JsonCreator
  public PreferencesValue(@JsonProperty(VALUE_FIELD) String value,
      @JsonProperty(VERSION_FIELD) long version, @JsonProperty(DELETED_FIELD) boolean deleted) {
    this.value = value;
    this.version = version;
    this.deleted = deleted;
  }

  /**
   * Get the value of the property.
   *
   * @return The value stored in the property.
   */
  @JsonProperty(VALUE_FIELD)
  public String getValue() {
    return value;
  }

  /**
   * Get the size of the object without the metadata.
   */
  @JsonIgnore
  public int getValueSize() {
    return value.length();
  }

  /**
   * Get the version of this property.
   */
  @JsonProperty(VERSION_FIELD)
  public long getVersion() {
    return version;
  }

  /**
   * @return If the value represents a deleted entry or not.
   */
  @JsonProperty(DELETED_FIELD)
  public boolean getDeleted() {
    return deleted;
  }

  /**
   * mark the entry for the delete.
   * @param version
   */
  public void setAsDelete(long version) {
    this.deleted = true;
    this.value = null;
    this.version = version;
  }

  /**
   * Set version for this property.
   */
  public void setVersion(long version) {
    this.version = version;
  }
}
